﻿using CsvHelper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace Magicodes.WeiChat.Infrastructure.MvcExtension.Results
{
    /// <summary>
    /// 导出CSV格式文件
    /// </summary>
    /// <typeparam name="T">实体数据类型</typeparam>
    //http://joshclose.github.io/CsvHelper/
    public class CsvFileResult<T> : FileResult where T : class
    {
        private IEnumerable<T> _data;

        public CsvFileResult(IEnumerable<T> data)
            : base("text/csv")
        {
            this.FileDownloadName = string.Format("{0}.csv",DateTime.Now.ToString("yyyyMMddHHmmss"));
            _data = data;
        }

        protected override void WriteFile(HttpResponseBase response)
        {
            var outPutStream = response.OutputStream;
            using (var streamWriter = new StreamWriter(outPutStream, System.Text.Encoding.UTF8))
            using (var writer = new CsvWriter(streamWriter))
            {
                writer.WriteHeader<T>();
                foreach (var item in _data)
                {
                    writer.WriteRecord(item);
                }
                streamWriter.Flush();
                response.Flush();
            }
        }
    }

}
